package com.matriq.cloudmanager;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import com.matriq.cloudmanager.R;
import com.matriq.cloudmanager.dialog.ConfirmDialog;
import com.matriq.cloudmanager.dialog.ConfirmDialog3;
import com.matriq.cloudmanager.dialog.DownloadDialog;
import com.matriq.cloudmanager.entity.StudyCommunion;
import com.matriq.cloudmanager.service.AccountService;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.lgpage.activity.BaseActivity;
import net.lgpage.dialog.DialogListener;
import net.lgpage.http.SwipeRefeshAsyncTask;
import net.lgpage.util.Cleaner;
import net.lgpage.util.IntentUtil;
import net.lgpage.util.PackageInfoUtil;

public class ClassLogActivity extends BaseActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_class_log);
		setViews();
		setEvents();
		loadData();
	}
	public void checkWPS(final String path){
		boolean able = PackageInfoUtil.isWpsAviliable(getActivity());
		if(able){
			try {
				startActivity(IntentUtil.openFile(new File(path)));
			} catch (FileNotFoundException e) {
				
			}
		}else{
			final ConfirmDialog3 cd = new ConfirmDialog3(getActivity());
			cd.setData("检测到你尚未安装WPS应用。\n是否去下载WPS?");
			cd.getBt_confirm().setText("去下载");
			cd.getBt_redownload().setText("其他应用\n打开");
			cd.getBt_confirm().setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					cd.dismiss();
					//Uri uri = Uri.parse("market://details?id=com.tencent.mm");
                    // 直接从指定网址下载
                     Uri uri = Uri.parse("http://fir.im/kjul");
                    Intent it = new Intent(Intent.ACTION_VIEW, uri); 
                    startActivity(it); 
				}
			});
			cd.getBt_redownload().setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					try {
						startActivity(IntentUtil.openFile(new File(path)));
					} catch (FileNotFoundException e) {
						
					}
				}
			});
			cd.show();
		}
	}
	android.support.v4.widget.SwipeRefreshLayout srl;
	TextView tv_title;
	android.support.v7.widget.RecyclerView rcy_class_log;
	ImageButton ll_back;
	LinearLayout ll_nothing;
	TextView tv_nothing;

	private void setViews() {
		srl = (android.support.v4.widget.SwipeRefreshLayout) this.findViewById(R.id.srl);
		tv_title = (TextView) this.findViewById(R.id.tv_title);
		rcy_class_log = (android.support.v7.widget.RecyclerView) this.findViewById(R.id.rcy_class_log);
		rcy_adp = new RcyAdp();
		rcy_class_log.setLayoutManager(new LinearLayoutManager(this));
		rcy_class_log.setAdapter(rcy_adp);
		ll_back = (ImageButton) this.findViewById(R.id.ll_back);
		ll_nothing = (LinearLayout) this.findViewById(R.id.ll_nothing);
		tv_nothing = (TextView) this.findViewById(R.id.tv_nothing);
	}

	private void setEvents() {
		srl.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				refeshRcyList();
			}
		});
		setNotingEvents();
	}

	Object obj;

	public void setData(Object obj) {
		this.obj = obj;
		tv_title.setText(null);
		tv_nothing.setText(null);
	}

	private class RcyViewHolder extends RecyclerView.ViewHolder {
		ImageView iv;
		TextView tv[] = new TextView[3];

		public RcyViewHolder(View view) {
			super(view);
		}
	}

	RcyAdp rcy_adp;

	class RcyAdp extends RecyclerView.Adapter<RcyViewHolder> {

		LayoutParams lp;

		@Override
		public int getItemCount() {
			if (rcylist == null)
				return 0;
			return rcylist.size();
		}

		public RcyAdp() {
			super();
			lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		}

		@Override
		public void onBindViewHolder(RcyViewHolder h, final int position) {
			final StudyCommunion obj = rcylist.get(position);
			h.tv[0].setText(obj.getFname());
			h.tv[1].setText("上传者:"+obj.getBy());
			h.tv[2].setText(obj.getDate());
			final String path = (String) load(obj.getUrl(), null);
			if(path!=null){
				h.tv[0].setTextColor(0xff989898);
				//h.itemView.setBackgroundColor(0xfff1f1f1);
			}else{
				h.tv[0].setTextColor(0xff282828);
				//h.itemView.setBackgroundColor(0xffffffff);
			}
			if(obj.getFname().contains(".doc")){
				h.iv.setImageResource(R.drawable.ic_doc);
			}else if(obj.getFname().contains(".ppt")){
				h.iv.setImageResource(R.drawable.ic_ppt);
			}else if(obj.getFname().contains(".xls")){
				h.iv.setImageResource(R.drawable.ic_xls);
			}else{
				h.iv.setImageResource(R.drawable.ic_doc);
			}
			h.itemView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					if(path == null){
						final ConfirmDialog dg = new ConfirmDialog(getActivity());
						dg.setData("是否下载该文件？");
						dg.setListener(new DialogListener() {
							
							@Override
							public void onDialogExecute(Object... os) {
								final DownloadDialog dd = new DownloadDialog(getActivity());
								dd.setData(obj.getFname()+"下载中...", obj.getUrl(),obj.getFname());
								dd.show();
								dd.setListener(new DialogListener() {
									
									@Override
									public void onDialogExecute(Object... os) {
										File file = (File) os[0];
										if(file!=null){
											putAppValue(obj.getUrl(), file.getPath());
										}
										rcy_adp.notifyItemChanged(position);
										checkWPS(file.getPath());
									}
								});
								dd.download();
								dg.dismiss();
							}
						});
						dg.show();
					}else{
						final ConfirmDialog3 dg = new ConfirmDialog3(getActivity());
						dg.setData("是否打开该文件？");
						dg.getBt_redownload().setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								final DownloadDialog dd = new DownloadDialog(getActivity());
								dd.setData(obj.getFname()+"下载中...", obj.getUrl(),obj.getFname());
								dd.show();
								dd.setListener(new DialogListener() {
									
									@Override
									public void onDialogExecute(Object... os) {
										File file = (File) os[0];
										if(file!=null){
											putAppValue(obj.getUrl(), file.getPath());
										}
										rcy_adp.notifyItemChanged(position);
										checkWPS(file.getPath());
									}
								});
								dd.download();
								dg.dismiss();
								dg.dismiss();
							}
						});
						dg.setListener(new DialogListener() {
							
							@Override
							public void onDialogExecute(Object... os) {
								checkWPS(path);
							}
						});
						dg.show();
					}
				}
			});
		}

		@SuppressLint("InflateParams")
		@Override
		public RcyViewHolder onCreateViewHolder(ViewGroup vgp, final int position) {
			View cv = getLayoutInflater().inflate(R.layout.rcy_class_log, null);
			cv.setLayoutParams(lp);
			RcyViewHolder h = new RcyViewHolder(cv);
			h.iv = (ImageView) cv.findViewById(R.id.iv);
			h.tv[0] = (TextView) cv.findViewById(R.id.tv0);
			h.tv[1] = (TextView) cv.findViewById(R.id.tv1);
			h.tv[2] = (TextView) cv.findViewById(R.id.tv2);
			return h;
		}
	}

	List<StudyCommunion> rcylist;
	RcyListTask rcylistTask;

	public void refeshRcyList() {
		if (rcylistTask != null) {
			rcylistTask.cancel(true);
		}
		rcylistTask = new RcyListTask(this);
		rcylistTask.setSwipeLayout(srl);
		rcylistTask.execute();
	}

	private class RcyListTask extends SwipeRefeshAsyncTask<List<StudyCommunion>> {

		public RcyListTask(Context context) {
			super(context);
		}


		@Override
		public List<StudyCommunion> doInBackgroundX(String... params) throws Exception {
			return AccountService.getService().study_communion();
		}

		@Override
		public void onPostExecuteX(List<StudyCommunion> result) {
			if (result == null) {
				return;
			} else {
				rcylist = result;
				checkListNoting();
				rcy_adp.notifyDataSetChanged();
			}
		}
	}

	private void loadData() {

		refeshRcyList();
	}
	
	private void setNotingEvents(){
		ll_nothing.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				changeListState(false);
				refeshRcyList();
			}
		});
	}
	
	private void checkListNoting(){
		if(rcylist == null||rcylist.size() == 0){
			changeListState(true);
		}else{
			changeListState(false);
		}
	}
	
	private void changeListState(boolean isnothing){
		if(!isnothing){
			ll_nothing.setVisibility(View.GONE);
			srl.setVisibility(View.VISIBLE);
		}else{
			ll_nothing.setVisibility(View.VISIBLE);
			srl.setVisibility(View.GONE);
		}
	}
	@Override
	public void onDestroy() {
		Cleaner.cleanTask(rcylistTask);
		
		super.onDestroy();
	}

}